package com.backend.system.service.processors.dictionary;

import cn.hutool.core.bean.BeanUtil;
import com.backend.system.beans.dictionary.DictionaryAddOrUpdateReq;
import com.backend.system.common.CustomException;
import com.backend.system.common.annotation.ProcessorBean;
import com.backend.system.common.enums.ActionTypeEnum;
import com.backend.system.common.enums.EnableStatusEnum;
import com.backend.system.common.processor.AbstractProcessorTemplate;
import com.backend.system.common.processor.ProcessorContext;
import com.backend.system.dao.entity.Dictionary;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * 字典新增或更新处理器
 *
 * @author backend-manage
 */
@Slf4j
@Component
@ProcessorBean(action = ActionTypeEnum.DICTIONARY_ADD_OR_UPDATE)
public class DictionaryAddOrUpdateProcessor extends AbstractProcessorTemplate<DictionaryAddOrUpdateReq, Boolean> {

    private Dictionary dictionary;

    @Override
    protected void init(ProcessorContext<DictionaryAddOrUpdateReq> context) {
        DictionaryAddOrUpdateReq req = context.getData();
        dictionary = null;

        boolean isAddDictionary = Objects.isNull(req.getId());
        if (!isAddDictionary) {
            dictionary = dictionaryService.getById(req.getId());
            if (Objects.isNull(dictionary)) {
                throw CustomException.argsError("字典不存在");
            }
        } else {
            dictionary = new Dictionary();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean handle(ProcessorContext<DictionaryAddOrUpdateReq> context) {
        DictionaryAddOrUpdateReq req = context.getData();
        BeanUtil.copyProperties(req, dictionary, "status");
        dictionary.setStatus(EnableStatusEnum.getInstance(req.getStatus()));
        return dictionaryService.saveOrUpdate(dictionary);
    }
}
